package com.woniu.service.impl;



import com.woniu.been.entity.Courses;
import com.woniu.been.entity.vo.MyClassVO;
import com.woniu.mapper.CourseMapper;
import com.woniu.service.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CourseService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    CourseMapper courseMapper;
    private final CourseRepository courseRepository;

    public CourseService(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    // 查看课程详情并增加观看次数
    public Courses viewCourse(Long courseId) {
        // 先增加观看次数
//        courseRepository.incrementViewCount(courseId);
        // 使用ZINCRBY命令原子性增加分数
        redisTemplate.opsForZSet().incrementScore("hot_courses:view_count", courseId, 1);
        // 可选：设置过期时间（如10分钟），避免冷门课程长期占用内存
        redisTemplate.expire("hot_courses:view_count", 2, TimeUnit.MINUTES);
        // 再查询课程详情（包含最新的观看次数）
        return courseRepository.findByCourseId(courseId);
    }
    /**
     * 获取热门课程列表（按观看次数排序）
     */
    public List<Courses> getHotCourses(int limit) {
        // 获取分数最高的N个课程ID（ZREVRANGE命令）
        Set<Object> courseIds = redisTemplate.opsForZSet()
                .reverseRange("hot_courses:view_count", 0, limit - 1);
        if (courseIds == null || courseIds.isEmpty()) {
            // 缓存中没有数据，从数据库查询并预热缓存
            System.out.println("hhhhhhhh");
            return loadHotCoursesFromDB(limit);
        }

        // 查询课程详情
        List<Long> ids = courseIds.stream()
                .map(id -> Long.parseLong(id.toString()))
                .collect(Collectors.toList());
        return courseRepository.findAllById(ids);
    }
    /**
     * 从数据库加载热门课程并预热缓存
     */
    private List<Courses> loadHotCoursesFromDB(int limit) {
        List<Courses> hotCourses = courseRepository.findTopByOrderByViewCountDesc (limit);
        // 预热缓存
        hotCourses.forEach(course -> {
            redisTemplate.opsForZSet().add(
                    "hot_courses:view_count",
                    course.getCourseId(),
                    course.getViewCount()
            );
        });
        return hotCourses;
    }

    /**
     * 获取课程的观看次数
     */
    public Long getViewCount(Long courseId) {
        Double score = redisTemplate.opsForZSet().score("hot_courses:view_count", courseId);
        return score != null ? score.longValue() : 0L;
    }

    /**
     * 定时任务：将Redis中的计数同步到数据库
     */
    @Scheduled(fixedRate = 60000) // 每分钟同步一次
    public void syncViewCountToDatabase() {
        // 获取所有课程ID和分数
        Set<ZSetOperations.TypedTuple<Object>> tuples = redisTemplate.opsForZSet()
                .rangeWithScores("hot_courses:view_count", 0, -1);
        System.out.println("自动执行"+tuples);
        if (tuples == null || tuples.isEmpty()) {
            return;
        }

        // 批量更新数据库
        tuples.forEach(tuple -> {
            Long courseId = Long.parseLong(tuple.getValue().toString());
            long viewCount = tuple.getScore().longValue();

            // 使用原生SQL批量更新，避免频繁调用save()
            System.out.println("courseId"+courseId+"viewCount"+viewCount);
            courseRepository.updateViewCount( (int) viewCount,courseId);
        });
    }

    public List<MyClassVO>  findMyCourseById(Integer userId) {

        List<MyClassVO> myClassVOList = courseMapper.findMyCourseById(userId);



        return myClassVOList;
    }

    public List<Integer> getMyCourseId(Integer userId) {
        return courseMapper.getMyCourseId(userId);
    }
}